<template>
  <div class="feedback-management-container">
    <h2>意见反馈管理</h2>
    
    <!-- 筛选区域 -->
    <div class="filter-area">
      <el-select 
        v-model="filterType" 
        placeholder="反馈类型" 
        clearable
        style="width: 120px; margin-right: 10px"
      >
        <el-option label="全部" value="all"></el-option>
        <el-option label="意见" value="suggestion"></el-option>
        <el-option label="建议" value="advice"></el-option>
        <el-option label="投诉" value="complaint"></el-option>
      </el-select>
      
      <el-select 
        v-model="filterStatus" 
        placeholder="处理状态" 
        clearable
        style="width: 120px; margin-right: 10px"
      >
        <el-option label="全部" value="all"></el-option>
        <el-option label="待处理" value="pending"></el-option>
        <el-option label="处理中" value="processing"></el-option>
        <el-option label="已解决" value="resolved"></el-option>
        <el-option label="已关闭" value="closed"></el-option>
      </el-select>
      
      <el-input
        v-model="searchQuery"
        placeholder="搜索反馈内容或用户"
        style="width: 300px; margin-right: 10px"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      
      <el-button 
        type="success" 
        icon="el-icon-download"
        @click="exportToExcel"
        style="margin-left: 10px"
      >
        导出Excel
      </el-button>
    </div>
    
    <!-- 反馈列表表格 -->
    <el-table :data="filteredFeedbacks" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="userName" label="用户" width="120"></el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="反馈内容"></el-table-column>
      <el-table-column prop="createTime" label="提交时间" width="180"></el-table-column>
      <el-table-column prop="handler" label="处理人" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            @click="handleProcess(scope.row)"
            v-if="scope.row.status !== 'resolved' && scope.row.status !== 'closed'"
          >
            处理
          </el-button>
          <el-button 
            size="mini" 
            type="info" 
            @click="handleView(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalFeedbacks"
    ></el-pagination>
    
    <!-- 处理反馈对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="feedbackForm" label-width="100px">
        <el-form-item label="反馈类型">
          <el-tag :type="getTypeTagType(feedbackForm.type)">
            {{ getTypeName(feedbackForm.type) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="用户">
          {{ feedbackForm.userName }}
        </el-form-item>
        <el-form-item label="反馈内容">
          <el-input
            type="textarea"
            :rows="4"
            readonly
            v-model="feedbackForm.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="处理人">
          <el-select v-model="feedbackForm.handler" placeholder="请选择处理人">
            <el-option
              v-for="admin in adminOptions"
              :key="admin.id"
              :label="admin.name"
              :value="admin.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="feedbackForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="处理中" value="processing"></el-option>
            <el-option label="已解决" value="resolved"></el-option>
            <el-option label="已关闭" value="closed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果">
          <el-input
            type="textarea"
            :rows="4"
            v-model="feedbackForm.result"
            placeholder="请输入处理结果"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFeedbackForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'FeedbackManagement',
  data() {
    return {
      feedbacks: [],
      filterType: 'all',
      filterStatus: 'all',
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '处理反馈',
      feedbackForm: {
        id: '',
        userName: '',
        type: '',
        content: '',
        createTime: '',
        handler: '',
        status: '',
        result: ''
      },
      adminOptions: [
        { id: '1001', name: '张三' },
        { id: '1002', name: '李四' },
        { id: '1003', name: '王五' }
      ],
      selectedIds: [], // 存储选中的反馈ID
      multipleSelection: [] // 存储选中的反馈项
    }
  },
  computed: {
    filteredFeedbacks() {
      return this.feedbacks.filter(feedback => {
        const matchesType = this.filterType === 'all' || feedback.type === this.filterType
        const matchesStatus = this.filterStatus === 'all' || feedback.status === this.filterStatus
        const matchesSearch = feedback.content.includes(this.searchQuery) || 
                            feedback.userName.includes(this.searchQuery)
        
        return matchesType && matchesStatus && matchesSearch
      }).slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      )
    },
    totalFeedbacks() {
      return this.feedbacks.length
    }
  },
  mounted() {
    this.fetchFeedbacks()
  },
  methods: {
    fetchFeedbacks() {
      // 模拟API调用获取反馈数据
      setTimeout(() => {
        this.feedbacks = [
          {
            id: 1,
            userName: '用户A',
            type: 'suggestion',
            content: '建议增加更多心理健康相关的文章',
            createTime: '2023-05-15 14:30:22',
            handler: '张三',
            status: 'processing',
            result: '已安排内容团队跟进'
          },
          {
            id: 2,
            userName: '用户B',
            type: 'complaint',
            content: '投诉某个用户发布不当言论',
            createTime: '2023-05-14 09:15:45',
            handler: '',
            status: 'pending',
            result: ''
          }
        ]
      }, 500)
    },
    getTypeName(type) {
      const typeMap = {
        'suggestion': '意见',
        'advice': '建议',
        'complaint': '投诉'
      }
      return typeMap[type] || type
    },
    getTypeTagType(type) {
      const typeMap = {
        'suggestion': '',
        'advice': 'info',
        'complaint': 'danger'
      }
      return typeMap[type] || ''
    },
    getStatusName(status) {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'resolved': '已解决',
        'closed': '已关闭'
      }
      return statusMap[status] || status
    },
    getStatusTagType(status) {
      const statusMap = {
        'pending': 'warning',
        'processing': '',
        'resolved': 'success',
        'closed': 'info'
      }
      return statusMap[status] || ''
    },
    handleSearch() {
      this.currentPage = 1
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleProcess(row) {
      this.dialogTitle = '处理反馈'
      this.feedbackForm = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    handleView(row) {
      this.dialogTitle = '反馈详情'
      this.feedbackForm = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    submitFeedbackForm() {
      // 模拟提交处理结果
      const index = this.feedbacks.findIndex(f => f.id === this.feedbackForm.id)
      if (index !== -1) {
        this.feedbacks.splice(index, 1, this.feedbackForm)
      }
      this.dialogVisible = false
      this.$message.success('处理结果已保存')
    },
    
    exportToExcel() {
      // 准备数据
      const data = this.feedbacks.map(item => ({
        'ID': item.id,
        '用户': item.userName,
        '反馈类型': this.getTypeName(item.type),
        '反馈内容': item.content,
        '提交时间': item.createTime,
        '处理人': item.handler,
        '处理状态': this.getStatusName(item.status),
        '处理结果': item.result
      }))
      
      // 创建工作簿
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.json_to_sheet(data)
      
      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '意见反馈')
      
      // 生成Excel文件并下载
      XLSX.writeFile(workbook, `意见反馈_${new Date().toLocaleDateString()}.xlsx`)
      
      this.$message.success('导出成功')
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.selectedIds = val.map(item => item.id)
    },
    
    // 单个删除
    handleDelete(row) {
      this.$confirm('确定要删除这条反馈吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.feedbacks.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.feedbacks.splice(index, 1)
          this.$message.success('删除成功')
        }
      }).catch(() => {})
    },
    
    // 批量删除
    handleBatchDelete() {
      this.$confirm(`确定要删除选中的${this.selectedIds.length}条反馈吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.feedbacks = this.feedbacks.filter(
          item => !this.selectedIds.includes(item.id)
        )
        this.selectedIds = []
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    
    // 导出选中项
    handleExportSelected() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      
      const selectedData = this.feedbacks.filter(
        item => this.selectedIds.includes(item.id)
      )
      
      const data = selectedData.map(item => ({
        'ID': item.id,
        '用户': item.userName,
        '反馈类型': this.getTypeName(item.type),
        '反馈内容': item.content,
        '提交时间': item.createTime,
        '处理人': item.handler,
        '处理状态': this.getStatusName(item.status),
        '处理结果': item.result
      }))
      
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.json_to_sheet(data)
      XLSX.utils.book_append_sheet(workbook, worksheet, '选中反馈')
      XLSX.writeFile(workbook, `选中反馈_${new Date().toLocaleDateString()}.xlsx`)
      
      this.$message.success('导出成功')
    }
  }
}
</script>

<style scoped>
.feedback-management-container {
  padding: 20px;
}

.filter-area {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>